<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Tymon\JWTAuth\Exceptions\JWTException;

class FirstController extends Controller
{
    /**
     * 注册
     * @return void
     * @Description
     * @author huj
     * @DateTime 2020-11-27 14:28:17
     */
    public function register()
    {
        $model = User::create([
            'nickname'=>'jwt-admin',
            'account'=>'jwt',
            'password'=>Hash::make(123456)
        ]);
        if ($model) {
        	return response()->json([
                'success' => true,
                'data' => $model
            ], 200);
        } else {
        	return response()->json([
                'error' => false,
                'data' => $model
            ], 400);
        }

    }

    /**
     * 测试其他
     * @param \Illuminate\Http\Request $request
     * @return void
     * @Description
     * @author huj
     * @DateTime 2020-11-27 11:07:59
     */
    public function getAuthUser(Request $request)
    {
        // dd($request->header('authorization'));
        $user = auth()->authenticate($request->header('authorization'));

        return response()->json(['user' => $user]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['account', 'password']);
        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {   
        try {
            auth()->logout();
        } catch (JWTException $e) {
            //throw $th;
        }
        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }


    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }



}
